const express = require('express');
const router = express.Router();
const { uploadBuffer, getSignedUrl } = require('../utils/oss');
const Core = require('@alicloud/pop-core');
const { success, fail } = require('../utils/response');

function base64ToBuffer(base64Str) {
    const matches = base64Str.match(/^data:(.+);base64,(.+)$/);
    if (!matches) throw new Error('Invalid base64 format');
    return Buffer.from(matches[2], 'base64');
}

router.post('/image', async (req, res) => {
    try {
        const { base64, fileName } = req.body;
        console.log('[Upload] 接收到上传请求');
        console.log('[Upload] fileName:', fileName);
        console.log('[Upload] base64 前 100 字符:', base64?.slice(0, 100));

        if (!base64 || !fileName) {
            console.warn('[Upload] base64 或 fileName 缺失');
            return fail(res, 'base64 或 fileName 不能为空');
        }

        const key = `images/${Date.now()}-${fileName}`;
        console.log(`[Upload] 生成文件名: ${key}`);

        const buffer = base64ToBuffer(base64);
        console.log('[Upload] buffer 长度:', buffer.length);

        await uploadBuffer(buffer, key);

        const signedUrl = getSignedUrl(key);

        console.log('[Upload] 上传成功，返回签名链接');

        return success(res, '上传成功', {
            url: signedUrl,
            key,
            expiresIn: 3600
        });

    } catch (err) {
        console.error('[Upload] 上传失败:', err.message);
        return fail(res, '上传失败');
    }
});
router.post('/sign-url', async (req, res) => {
    try {
        const { keys } = req.body;

        if (!Array.isArray(keys) || keys.length === 0) {
            return fail(res, 'keys 参数必须是非空数组');
        }

        const result = keys.map((key) => {
            if (typeof key !== 'string' || !key.trim()) {
                return { key, error: '无效 key' };
            }
            try {
                const url = getSignedUrl(key);
                return { key, url };
            } catch (err) {
                return { key, error: '签名失败' };
            }
        });

        return success(res, '批量签名 URL 生成成功', result);
    } catch (err) {
        console.error('[SignUrl] 批量生成失败:', err);
        return fail(res, '批量签名 URL 生成失败');
    }
});

router.post('/sts-token', async (req, res) => {
    try {
        const client = new Core({
            accessKeyId: process.env.OSS_ACCESS_KEY_ID,
            accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
            endpoint: 'https://sts.aliyuncs.com',
            apiVersion: '2015-04-01',
        });
        console.log("🚀 ~ router.post ~ client:", client)

        const roleArn = process.env.OSS_ROLE_ARN;
        console.log("🚀 ~ router.post ~ roleArn:", roleArn)
        const roleSessionName = 'session-' + Date.now();

        const policy = {
            Version: '1',
            Statement: [
                {
                    Action: ['oss:PutObject', 'oss:PutObjectAcl', 'oss:GetObject'],
                    Effect: 'Allow',
                    Resource: [`acs:oss:*:*:${process.env.OSS_BUCKET}/*`],
                },
            ],
        };

        const params = {
            RoleArn: roleArn,
            RoleSessionName: roleSessionName,
            DurationSeconds: 3600,
            Policy: JSON.stringify(policy),
        };

        const result = await client.request('AssumeRole', params, { method: 'POST' });

        console.log("🚀 ~ router.post ~ result:", result)
        return success(res, 'STS Token 获取成功', {
            credentials: result.Credentials,
            expiration: result.Credentials.Expiration,
        });
    } catch (error) {
        console.error('[STS] 获取临时访问凭证失败:', error);
        return fail(res, '获取临时访问凭证失败');
    }
});
module.exports = router;
